package com.cheer.dao;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cheer.entity.User;
import com.cheer.enums.RoleEnum;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

/**
 * 用户表
 *
 * @author lx
 */
@Mapper
@Repository
public interface UserDao extends BaseMapper<User> {

    default User selectOneByUsername(String username) {
        return selectOne(new QueryWrapper<User>()
                .eq("username", username)
                .last("limit 1"));
    }

    default IPage<User> selectPage(Integer pageNum, Integer pageSize, String keyword) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        keyword = StringUtils.trimToNull(keyword);
        queryWrapper.eq("role", RoleEnum.USER.getCode());
        if (keyword != null) {
            String finalKeyword = keyword;
            queryWrapper.and(wrapper -> wrapper.like("name", finalKeyword)
                    .or().eq("username", finalKeyword));
        }

        return selectPage(new Page<>(pageNum, pageSize), queryWrapper);
    }

    void updateUser(User user);
}
